"""
    对接第三方短信业务接口
"""
import random

import requests
import time
import base64
import hashlib


class YunTongXunAPI:
    def __init__(self, account_sid, auth_token, app_id, template_id):
        self.account_sid = account_sid
        self.auth_token = auth_token
        self.app_id = app_id
        self.template_id = template_id

    def get_url(self):
        """获取通信url"""
        url = f'https://app.cloopen.com:8883/2013-12-26/Accounts/{self.account_sid}/SMS/TemplateSMS?sig={self.get_sid()}'
        return url

    def get_headers(self):
        """获取请求头"""
        auth = base64.b64encode((self.account_sid + ':' + time.strftime("%Y%m%d%H%M%S")).encode()).decode()
        json_data = {
            "Accept": "application/json",
            "Content-Type": "application/json;charset=utf-8",
            # requests模块会自行处理
            # "Content-Length":"256",
            "Authorization": auth
        }
        return json_data

    def get_body(self, phone, code):
        """获取请求体"""
        data = {
            "to": phone,
            "appId": self.app_id,
            "templateId": self.template_id,
            # 验证码为{1},请于{2}分钟内输入
            "datas": [code, "10"]
        }
        return data

    def run(self, phone, code):
        """程序入口函数"""
        url = self.get_url()
        data = self.get_body(phone, code)
        headers = self.get_headers()
        return requests.post(url=url, headers=headers, json=data).json()

    def get_sid(self):
        """功能函数，生成请求地址中的sid查询字符串sig
            md5(账户id+授权名牌+时间辍)
        """
        s = self.account_sid + self.auth_token + time.strftime("%Y%m%d%H%M%S")
        m = hashlib.md5()
        m.update(s.encode())
        return m.hexdigest().upper()


if __name__ == '__main__':
    config = {
        "account_sid": "2c94811c9035ff9f01914c30ac4c3dc3",
        "auth_token": "818d94bd842747829f01b44afb06212a",
        "app_id": "2c94811c9035ff9f01914c30ae073dca",
        "template_id": "1",
    }
    phone = "13572942503"
    code = random.randint(1000, 9999)
    ytx = YunTongXunAPI(**config)
    print(ytx.run(phone, code))
